import Vue from 'vue'
import Router from 'vue-router'
import front from '@/router/front'
import store from '@/store/index'
import backStage from '@/router/backStage'
import defaultRouter from '@/router/default'
import VueCookies from 'vue-cookies'

Vue.use(Router)
console.log(store.state)
    // 路由配置
const RouterConfig = {
    // mode: 'history',
    routes: new Set([...front, ...backStage, ...defaultRouter]) //前后台路由合并
};

// console.log(RouterConfig)
export const router = new Router(RouterConfig);

//无需获取登录信息可直接进入的白名单
router.beforeEach((to, from, next) => {
    let that = this;
    let whiteList = ["test"];
    let toName = to.path.replace(/^\//, '').split('/')[0];
    console.log(to);

    if (whiteList.includes(toName)) { //白名单
        next();
    } else {
        // 获取登录状态
        let loginInfo = VueCookies.get("loginInfo");
        console.log(loginInfo);
        // 后台
        if (toName == 'backstage') {
            // 用户已经登录
            if (loginInfo) {
                // 后台页面的权限，当前用户是否拥有路由对应的权限
                let hasPermission = loginInfo.roles.some(role => {
                    console.log(to.meta.roles, role)
                    return to.meta.roles.includes(role);
                })

                if (hasPermission) {
                    next();
                } else {
                    next({
                        path: '/403',
                        replace: true
                    })
                }
            } else {
                next({
                    path: '/login',
                    replace: true
                })
            }
        } else if ((toName == 'login' || toName == 'register') && loginInfo) {
            // 如果已经登录了，则不允许进入登录或者注册页面
            next({
                path: '/backstage',
            })
        } else {
            // 前台无需权限校验
            next();
        }
    }
});

router.afterEach((to, from, next) => {
    window.scrollTo(0, 0);
});